package com.lyc.iotdb.common.iot;

import cn.hutool.core.date.DateUtil;
import com.lyc.iotdb.common.annotation.IotTableName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * Iotdb 数据载入方法
 *
 * @author kisang
 * @version 1.0
 * @date 2023/11/21 15:47
 */
public interface IotdbRecordable {
    Logger logger = LoggerFactory.getLogger(IotdbRecordable.class);

    /**
     * 数据载入方法
     *
     * @return Record
     */
    default IotdbRecord toRecord() {
        IotdbRecord iotdbRecord = new IotdbRecord();
        // 当前时间
        iotdbRecord.setTime(DateUtil.currentSeconds() * 1000);
        Class<? extends IotdbRecordable> aClass = this.getClass();
        IotTableName name = this.getClass().getAnnotation(IotTableName.class);
        iotdbRecord.setDeviceId(name.value());
        Field[] declaredFields = aClass.getDeclaredFields();
        List<String> measurements = new ArrayList<>();
        List<Object> records = new ArrayList<>();
        List<String> types = new ArrayList<>();
        try {
            for (Field field : declaredFields) {
                measurements.add(field.getName());
                String methodNamePro = field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1);
                Method methodName = this.getClass().getMethod("get" + methodNamePro);
                records.add(methodName.invoke(this));
                types.add(methodName.getReturnType().getName());
            }
            iotdbRecord.setMeasurementsList(measurements);
            iotdbRecord.setValuesList(records);
            iotdbRecord.setTypeList(types);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("IoTDB实体类转换异常：{}", e.getMessage());
        }
        return iotdbRecord;
    }
}
